
import { ref, onMounted, onUnmounted } from 'vue'

export default function useAutoScroll(containerRef, immediate = true) {
  const scrollHeight = ref(0)
  const isAutoScrolling = ref(false)
  const userScrolledUp = ref(false)
  const isActive = ref(true)
  const isNearBottom = ref(false)

  const scrollToBottom = (options) => {
    if (!containerRef.value) return
    isAutoScrolling.value = true
    containerRef.value.scrollTo({
      top: containerRef.value.scrollHeight,
      behavior: options?.behavior || 'smooth'
    })
    setTimeout(() => isAutoScrolling.value = false, 500)
  }

  const handleScroll = () => {
    if (!containerRef.value) return  // 移除isActive检查，保持滚动检测

    const { scrollTop, clientHeight, scrollHeight } = containerRef.value
    isNearBottom.value = scrollTop + clientHeight >= scrollHeight - 100

    if (!isAutoScrolling.value) {
      userScrolledUp.value = scrollTop + clientHeight < scrollHeight
    }

    if (isNearBottom.value && !isAutoScrolling.value) {
      userScrolledUp.value = false
    }
  }

  const observer = new MutationObserver(() => {
    if (!isActive.value) return  // 保持自动滚动受控
    const newHeight = containerRef.value?.scrollHeight || 0
    if (newHeight !== scrollHeight.value) {
      scrollHeight.value = newHeight
      if (!userScrolledUp.value) {
        scrollToBottom()
      }
    }
  })

  const init = () => {
    if (containerRef.value) {
      containerRef.value.addEventListener('scroll', handleScroll)
      observer.observe(containerRef.value, {
        childList: true,
        subtree: true,
        attributes: true
      })
      if (immediate && isActive.value) {
        scrollToBottom({ behavior: 'auto' })
      }
    }
  }

  onMounted(init)

  onUnmounted(() => {
    if (containerRef.value) {
      containerRef.value.removeEventListener('scroll', handleScroll)
      observer.disconnect()
    }
  })

  return {
    scrollToBottom,
    isNearBottom,
    isActive,
    start: () => isActive.value = true,
    stop: () => isActive.value = false
  }
}
